package bibliotecas;

import java.sql.*;
import java.util.ArrayList;

public class JConexao {

	private Connection connection = null;
	private Statement statement = null;
	private ResultSet resultSet = null;
	public String erro = "";
	
	public JConexao(String DRIVER,String URL_CONEXAO){
		try {
			Class.forName(DRIVER);
			connection = DriverManager.getConnection(URL_CONEXAO);
		} catch (Exception e) {
			erro = e.getMessage();
		}
	}
	
	public JConexao(String DRIVER,String URL_CONEXAO,String USUARIO,String SENHA){
		try {
			Class.forName(DRIVER);
			connection = DriverManager.getConnection(URL_CONEXAO,USUARIO,SENHA);
		} catch (Exception e) {
			erro = e.getMessage();
		}
	}
	
	public Object[][] Select(String SQL){
		Object dados[][] = null;
		ArrayList<Object[]> tmp = new ArrayList<Object[]>(); 
		
		if(connection != null){
			System.out.println(SQL);
			try {
				statement = connection.createStatement();
				resultSet = statement.executeQuery(SQL);
				while(resultSet.next()){
					tmp.add(new Object[resultSet.getMetaData().getColumnCount()]);
					for(int i = 0;i < tmp.get(tmp.size() - 1).length;i++){
						tmp.get(tmp.size() - 1)[i] = resultSet.getObject(i + 1);
					}
				}
				dados = new Object[tmp.size()][resultSet.getMetaData().getColumnCount()];
				for(int i = 0;i < dados.length;i++){
					for(int x = 0;x < dados[i].length;x++){
						dados[i][x] = tmp.get(i)[x];
					}
				}
			} catch (SQLException e) {
				erro = e.getMessage();
			}
			
		}
		
		return dados;
	}
	
	public void Update(String SQL){
		if(connection != null){
			System.out.println(SQL);
			try {
				statement = connection.createStatement();
				statement.executeUpdate(SQL);
			} catch (SQLException e) {
				erro = e.getMessage();
			}			
		}
	}
	
	public void Close(){
		try {
			if (connection != null)
				connection.close();
			if (statement != null)
				statement.close();
			if (resultSet != null)
				resultSet.close();
		} catch (SQLException e) {
			erro = e.getMessage();
		}
	}
	
}
